# This file is part of Nephite Exchange.
#
# Nephite Exchange is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# Nephite Exchange is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Nephite Exchange.  If not, see <http://www.gnu.org/licenses/>.

use strict;

use DBI;
use Text::CSV;

####################################### Some Global Declarations

# Today's date.
my $date = `date +%Y-%m-%d`;
chomp($date);

# MySQL connection
my $host = 'localhost';
my $user = 'nephiteexchange';
my $pass = 'nephiteexchange';
my $db   = 'nephiteexchange';

if ( $ARGV[0] eq 'prod' ) {
	$host = 'nephiteexchange.db.5459258.hostedresource.com';
	$user = 'nephiteexchange';
	$pass = 'ChUm6cRa!';
	$db   = 'nephiteexchange';
}

my $sql = DBI->connect("DBI:mysql:database=$db;hostname=$host", $user, $pass)
  or die "Couldn't connect to database: " . DBI->errstr;


####################################### Run the Updates
updateExchangeRates();
updateBarleyRates();
updateLastUpdated();

exit(0);

sub updateExchangeRates {

	# We use this to clean up the lines we get back.
	my $cleanLine =
	    'sed -e \'s/<\/TR>/\n/g\' '
	  . '-e \'s/<[^>]*>/ /g\' '
	  . '-e \'s/ [ ]*/ /g\' '
	  . '-e \'s/Last Updated: [^)]*)//g\' '
	  . '-e \'s/Country.*Change //g\' | '
	  . 'sed -e \'s/^[ \t]*//g\'';

	# We use this to find the right line.
	my $findLine = "fgrep \"Last Updated: \"";

	# We use this to parse the HTML table and format the lines.
	my $cleanLine =
	    'sed -e \'s/<\/TR>/\n/g\' '
	  . "-e 's/<[^>]*>/ /g' "
	  . "-e 's/ [ ]*/ /g' "
	  . "-e 's/Last Updated: [^)]*)//g' "
	  . "-e 's/Country.*Change //g' | "
	  . "sed -e 's/^[ \t]*//g'";

	# The url and values we'll glean from.
	my $baseURL    = "http://www.exchangerate.com/world_rates.html?cont=";
	my @continents = (
		'Africa',          'Central%20America/Caribbean',
		'Asia',            'Europe',
		'North%20America', 'Australia/Oceania',
		'Middle%20East',   'South%20America'
	);

	# Read in each of the urls, one at a time.
	foreach (@continents) {
		open( INPUT,
			"wget -q -O - $baseURL$_ 2>&1 | $findLine | $cleanLine |" );

		while (<INPUT>) {
			chomp;
			chomp;

			# Skip lines that only contain whitespace.
			if ( $_ =~ /^\s*$/ ) {
				next;
			}

			my @vals = split( / +/, $_ );

			my $change = pop(@vals);
			if ( $change eq '-' ) {
				$change = pop(@vals);
			}

			my $previousDay = pop(@vals);
			my $today       = pop(@vals);
			my $ISO         = pop(@vals);
			my $name        = pop(@vals);
			my $country     = join( ' ', @vals );

			my $query =
			    "REPLACE INTO ExchangeRate VALUES ("
			  . $sql->quote($country) . ","
			  . $sql->quote($name) . ","
			  . $sql->quote($ISO) . ","
			  . $sql->quote($today) . ");";

			$sql->do($query);
		}

		close(INPUT);
	}

}

sub updateBarleyRates {

	# The URL where we'll get the barley csv.
	my $barleyURL =
	  "http://www.imf.org/external/np/res/commod/externaldata.csv";

	my $csv          = Text::CSV->new();
	my $barleyColumn = -1;
	my @cols;

	# Eventually one of the CSV columns will have PBARL and the last
	# row in that column will contain the current price.
	open( BARLEY, "wget -q -O - $barleyURL |" );
	while (<BARLEY>) {

		if ( $csv->parse($_) ) {
			@cols = $csv->fields();

			if ( $barleyColumn == -1 ) {
				foreach ( my $x = 0 ; $x < scalar(@cols) ; $x++ ) {
					if ( $cols[$x] =~ m/PBARL/ ) {
						$barleyColumn = $x;
					}
				}
			}
		}
	}
	close(BARLEY);

	# If we found the colum, the last line should have the value.
	if ( $barleyColumn != -1 ) {
		$sql->do( "UPDATE BarleyExchange SET CurrentRate = "
			  . $cols[$barleyColumn]
			  . ";" );
	}
}

sub updateLastUpdated {
	$sql->do("UPDATE LastUpdated SET LastUpdated = NOW();");
}
